package com.quanyan.operative.mq.Consumer;

import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.quanyan.api.APIResponse;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.mq.enums.MqConsumerStatus;
import com.quanyan.mq.mq.consumer.AbstractMqConsumer;
import com.quanyan.mq.mq.consumer.MqTopic;
import com.quanyan.operative.constants.OperativeConstant;
import com.quanyan.operative.service.SnatchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * Created by huadongyang on 2017/1/3.
 */
@Component("generateSnatchNumConsumer")
public class GenerateSnatchNumConsumer extends AbstractMqConsumer {
    private static final Logger logger = LoggerFactory.getLogger(GenerateSnatchNumConsumer.class);
    /**
     * mq服务器地址
     */
    @Value("${mq.nameServer.address}")
    private String nameServerAddress;

    @Autowired
    private SnatchService snatchService;

    @PostConstruct
    void run() {
        logger.info("夺宝生成奖品号mq消费--消息启动{}", nameServerAddress);
        super.start();
    }

    @Override
    protected MqConsumerStatus process(List<MessageExt> messages, ConsumeConcurrentlyContext context) {
        logger.info("鸟蛋夺宝生成夺宝号开始---------------------------------》接收消息");
        MessageExt messageExt = messages.get(0);
        //处理鸟蛋夺宝生成夺宝号任务消息
        if (OperativeConstant.GENERATE_SNATCH_NUM_TOPIC.equals(messageExt.getTopic()) && OperativeConstant.GENERATE_SNATCH_NUM_TAG.equals(messageExt.getTags())) {
            byte[] bodyByte = messageExt.getBody();
            String msgId = messageExt.getMsgId();//mq内部id
            logger.info("mq消息id:{},业务key :{}",msgId,messageExt.getKeys());
            Integer snatchNum = (Integer) ObjectUtil.toObject(bodyByte);
            logger.info("snatchNum:",snatchNum);
            snatchService.generateSnatchNum(snatchNum);
        }
        logger.info("用户设置结束---------------------------------》接收消息");
        return MqConsumerStatus.CONSUMER_SUCCESS;
    }

    @Override
    protected String getConsumerGroup() {
        return OperativeConstant.GENERATE_SNATCH_NUM_GROUP;
    }

    @Override
    protected String getNameServerAddress() {
        return this.nameServerAddress;
    }

    @Override
    protected String getInstanceName() {
        return OperativeConstant.GENERATE_SNATCH_NUM_INSTANCE;
    }

    @Override
    protected MqTopic[] getMqTopics() {
        MqTopic[] mqTopics = new MqTopic[1];
        mqTopics[0] = new MqTopic(OperativeConstant.GENERATE_SNATCH_NUM_TOPIC, OperativeConstant.GENERATE_SNATCH_NUM_TAG);
        return mqTopics;
    }
}
